package com.cmcc.linlaker.ui.upload;

import android.Manifest;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.support.v4.content.FileProvider;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.util.Log;
import android.view.View;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

import com.amap.api.location.AMapLocation;
import com.amap.api.location.AMapLocationClient;
import com.amap.api.location.AMapLocationClientOption;
import com.amap.api.location.AMapLocationListener;
import com.android.volley.VolleyError;
import com.cmcc.linlaker.LoadingActivity;
import com.cmcc.linlaker.R;
import com.cmcc.linlaker.application.LinhuApp;
import com.cmcc.linlaker.bean.BaseBean;
import com.cmcc.linlaker.bean.DictBean;
import com.cmcc.linlaker.bean.ImageUploadBean;
import com.cmcc.linlaker.crop.ClipImageActivity;
import com.cmcc.linlaker.crop.util.ActivityResultHelper;
import com.cmcc.linlaker.fragment.RoundFragment;
import com.cmcc.linlaker.http.ApiDefine;
import com.cmcc.linlaker.permission.GPermisson;
import com.cmcc.linlaker.permission.PermissionCallback;
import com.cmcc.linlaker.ui.query.ImageScanActivity;
import com.cmcc.linlaker.ui.query.ProjectListActivity;
import com.cmcc.linlaker.ui.query.bean.QueryProjectBean;
import com.cmcc.linlaker.ui.upload.adapter.ImageAdapter;
import com.cmcc.linlaker.ui.upload.bean.CheckingTaskBean;
import com.cmcc.linlaker.ui.upload.bean.ImageBean;
import com.cmcc.linlaker.ui.upload.bean.RegionTextBean;
import com.cmcc.linlaker.ui.upload.bean.UploadQuestionBean;
import com.cmcc.linlaker.utils.BarUtils;
import com.cmcc.linlaker.utils.DensityUtil;
import com.cmcc.linlaker.utils.IntentUtils;
import com.cmcc.linlaker.utils.PhotoUtils;
import com.cmcc.linlaker.utils.PictureUtil;
import com.cmcc.linlaker.utils.SPHelper;
import com.cmcc.linlaker.utils.StringUtils;
import com.cmcc.linlaker.utils.ToastUtils;
import com.cmcc.linlaker.utils.Utils;
import com.cmcc.linlaker.view.GridSpacingItemDecoration;
import com.cmcc.linlaker.volley.GsonRequestHelper;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.google.gson.reflect.TypeToken;
import com.tianditu.android.maps.OnGetPoiResultListener;
import com.tianditu.android.maps.PoiInfo;
import com.tianditu.android.maps.PoiSearch;
import com.zhy.http.okhttp.OkHttpUtils;
import com.zhy.http.okhttp.callback.StringCallback;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.File;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import okhttp3.Call;

public class UploadZxActivity extends AppCompatActivity implements View.OnClickListener {
    private UploadQuestionBean.UploadQuestionData problemBean;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_upload_zx);

        BarUtils.initStatusBar(this);

        initView();
    }

    private ImageAdapter adapter;
    private List<ImageBean> bmpList = new ArrayList<>();
    private RecyclerView recycler_pic;

    private TextView text_title, text_big_type, text_small_type;

    private TextView text_project_name, text_input_info, textRegion;
    private EditText edit_address, edit_description;

    public void initView() {
        problemBean = (UploadQuestionBean.UploadQuestionData) getIntent().getSerializableExtra("problemBean");

        text_title = findViewById(R.id.text_title);
        text_big_type = findViewById(R.id.text_big_type);
        text_small_type = findViewById(R.id.text_small_type);

        getProblemDetail();

        textRegion = findViewById(R.id.textRegion);
        recycler_pic = findViewById(R.id.recycler_pic);
        setRecyclerView(recycler_pic, bmpList);

        addButton();

        text_input_info = findViewById(R.id.text_input_info);
        edit_address = findViewById(R.id.edit_address);
        text_project_name = findViewById(R.id.text_project_name);
        edit_description = findViewById(R.id.edit_description);
        edit_description.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {

            }

            @Override
            public void afterTextChanged(Editable s) {
                String content = edit_description.getText().toString();
                int length = content.length();
                text_input_info.setText(length + "/100");
            }
        });
        findViewById(R.id.text_upload).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                upload();
            }
        });
        findViewById(R.id.layout_address_icon).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
//                getLocationInfo();
            }
        });

        getGpsInfo();
    }

    /**
     * 获取经纬度
     */
    private void getGpsInfo() {
        getCurrentLocationLatLng();
    }

    //声明AMapLocationClient类对象
    private AMapLocationClient mLocationClient = null;
    //声明AMapLocationClientOption对象
    public AMapLocationClientOption mLocationOption = null;

    /**
     * 初始化定位并设置定位回调监听
     */
    private void getCurrentLocationLatLng() {
        //初始化定位
        mLocationClient = new AMapLocationClient(this);
        //设置定位回调监听
        mLocationClient.setLocationListener(mLocationListener);
        //初始化AMapLocationClientOption对象
        mLocationOption = new AMapLocationClientOption();
        // 同时使用网络定位和GPS定位,优先返回最高精度的定位结果,以及对应的地址描述信息
        mLocationOption.setLocationMode(AMapLocationClientOption.AMapLocationMode.Hight_Accuracy);
        //设置定位间隔,单位毫秒,默认为2000ms，最低1000ms。默认连续定位 切最低时间间隔为1000ms
        mLocationOption.setOnceLocation(false);
        mLocationOption.setInterval(2000);
        //给定位客户端对象设置定位参数
        mLocationClient.setLocationOption(mLocationOption);
        //启动定位
        mLocationClient.startLocation();
    }

    private String currentPlaceName;

    /**
     * 定位回调监听器
     */
    public AMapLocationListener mLocationListener = new AMapLocationListener() {
        @Override
        public void onLocationChanged(AMapLocation amapLocation) {
            if (amapLocation != null) {
                if (amapLocation.getErrorCode() == 0) {
                    //定位成功回调信息，设置相关消息
                    amapLocation.getLocationType();//获取当前定位结果来源，如网络定位结果，详见定位类型表
                    latitude = amapLocation.getLatitude();//获取纬度
                    longitude = amapLocation.getLongitude();//获取经度
                    amapLocation.getAccuracy();//获取精度信息

                    currentPlaceName = amapLocation.getAddress();
//                    textRegion.setText(amapLocation.getDistrict());
                } else {
                    Toast.makeText(UploadZxActivity.this, "为正常使用，请开启定位服务", Toast.LENGTH_SHORT).show();
                }
            }
        }
    };

    /**
     * 上报
     */
    public void upload() {
        uploadData();

//        String address = edit_address.getText().toString();
//        if (latitude != 0 && longitude != 0) {
//            uploadData();
//        } else {
//            getLatLng(address);
//        }

    }


    private void setRecyclerView(final RecyclerView recycler_view, final List<ImageBean> itemList) {
        recycler_view.setHasFixedSize(true);
        recycler_view.setLayoutManager(new GridLayoutManager(this, 4));

        recycler_view.setNestedScrollingEnabled(false);
        recycler_view.addItemDecoration(new GridSpacingItemDecoration(4, DensityUtil.dip2px(this, 10), true));
        adapter = new ImageAdapter(this, itemList);
        adapter.setOnItemClickListener(new ImageAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(int position) {
                if (itemList.get(position).type == 0) {
                    selectPictures();
                } else {
                    Intent intent = new Intent(UploadZxActivity.this, ImageScanActivity.class);
                    intent.putExtra("imageBeanList", imageList);
                    intent.putExtra("position", position);
                    startActivity(intent);
                }
            }

            @Override
            public void onItemDeleteClick(int position) {
                deletePic(position);
            }
        });
        recycler_view.setAdapter(adapter);
    }

    /**
     * 选择图片
     */
    public void selectPictures() {
        if (Build.VERSION.SDK_INT >= 23) {
            GPermisson.with(this)
                    .permisson(new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE, Manifest.permission.CAMERA})
                    .callback(new PermissionCallback() {
                        @Override
                        public void onPermissionGranted() {
                            showSelectDialog();
                        }

                        @Override
                        public void shouldShowRational(String permisson) {
                        }

                        @Override
                        public void onPermissonReject(String permisson) {
                        }
                    }).request();
        } else {
            showSelectDialog();
        }

    }

    private void showSelectDialog() {
        final String[] items = {"相机", "相册"};
        AlertDialog.Builder builder = new AlertDialog.Builder(
                this);
        builder.setTitle("选择图片")
                .setItems(items, new DialogInterface.OnClickListener() {

                    @Override
                    public void onClick(DialogInterface dialog, int which) {

                        if (which == 0) {// 相机
                            takePhoto();
                        } else if (which == 1) {// 相册
                            choosePhoto();
                        }

                    }
                }).create().show();
    }

    public static final int RC_TAKE_PHOTO = 1;
    public static final int RC_CHOOSE_PHOTO = 2;
    public static final int RC_CROP_PHOTO = 3;

    private File fileUri = new File(Environment.getExternalStorageDirectory().getPath() + "/lh_photo.jpg");
    private File fileCropUri = new File(Environment.getExternalStorageDirectory().getPath() + "/lh_crop_photo.jpg");
    private Uri imageUri;
    private Uri cropImageUri;

    /**
     * 拍照
     */
    private void takePhoto() {
        imageUri = Uri.fromFile(fileUri);
        //通过FileProvider创建一个content类型的Uri
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
            imageUri = FileProvider.getUriForFile(this, "com.cmcc.linlaker.fileprovider", fileUri);
        }

        PhotoUtils.takePicture(this, imageUri, RC_TAKE_PHOTO);
    }

    /**
     * 打开相册
     */
    private void choosePhoto() {
        PhotoUtils.openPic(this, RC_CHOOSE_PHOTO);
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == RESULT_OK) {
            if (requestCode == RC_TAKE_PHOTO) {
                gotoClipActivity(Uri.fromFile(fileUri));
//                cropImageUri = Uri.fromFile(fileCropUri);

//                PhotoUtils.cropImageUri(this, imageUri, cropImageUri, 1, 1, LoadingActivity.screenWidth, LoadingActivity.screenWidth, RC_CROP_PHOTO);
            } else if (requestCode == RC_CHOOSE_PHOTO) {
                gotoClipActivity(data.getData());
//                cropImageUri = Uri.fromFile(fileCropUri);
//                Uri newUri = Uri.parse(PhotoUtils.getPath(this, data.getData()));
//                if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
//                    newUri = FileProvider.getUriForFile(this, "com.cmcc.linlaker.fileprovider", new File(newUri.getPath()));
//                }
//
//                PhotoUtils.cropImageUri(this, newUri, cropImageUri, 1, 1, LoadingActivity.screenWidth, LoadingActivity.screenWidth, RC_CROP_PHOTO);
            } else if (requestCode == RC_CROP_PHOTO) {
                Bitmap myBitmap = PhotoUtils.getBitmapFromUri(cropImageUri, this);

                String fileName = PictureUtil.getCharacterAndNumber();
                File file = new File(PictureUtil.PHOTO_DIR, fileName + ".png");
                PictureUtil.saveMyBitmap(myBitmap, file);

                addBmp(myBitmap);

                uploadPic(fileName + ".png", file);
            }
        } else if (resultCode == 1000) {
            projectData = (QueryProjectBean.QueryProjectData) data.getSerializableExtra("bean");
            if (projectData != null) {
                text_project_name.setText(projectData.name);
            }
        }
    }

    /**
     * 打开截图界面
     */
    public void gotoClipActivity(Uri uri) {
        if (uri == null) {
            return;
        }
        ClipImageActivity.goToClipActivity(UploadZxActivity.this, uri, new ActivityResultHelper.Callback() {
            @Override
            public void onActivityResult(int resultCode, Intent intent) {
                if (intent == null) {
                    return;
                }

                final Uri uri = intent.getData();
                if (uri == null) {
                    return;
                }
                Bitmap myBitmap = PhotoUtils.getBitmapFromUri(uri, UploadZxActivity.this);

                String fileName = PictureUtil.getCharacterAndNumber();
                File file = new File(PictureUtil.PHOTO_DIR, fileName + ".png");
                PictureUtil.saveMyBitmap(myBitmap, file);

                addBmp(myBitmap);

                uploadPic(fileName + ".png", file);
            }
        });
    }

    private ArrayList<ImageUploadBean> imageList = new ArrayList<>();

    private void uploadPic(String fileName, File file) {
        Map<String, String> headers = new HashMap<>();
        headers.put("authToken", SPHelper.getAuthToken());
        headers.put("from", "android");
        OkHttpUtils.post()
                .headers(headers)
                .addFile("file", fileName, file)
                .url(ApiDefine.UPLOAD_PIC)
                .build()
                .execute(new StringCallback() {
                    @Override
                    public void onError(Call call, Exception e, int id) {
                        Log.e("onError:", "onError");
                    }

                    @Override
                    public void onResponse(String response, int id) {
                        Log.e("url:", response);
                        String jsonStr = response;
                        Gson gson = new GsonBuilder().create();
                        ImageUploadBean bean = gson.fromJson(jsonStr, new TypeToken<ImageUploadBean>() {
                        }.getType());

                        if (bean != null) {
                            imageList.add(bean);
                        }

                    }
                });
    }

    private QueryProjectBean.QueryProjectData projectData;

    private int projectType = 1;

    private void selectProjectType() {
        projectType = 1;
        Intent intent = new Intent(this, ProjectListActivity.class);
        startActivityForResult(intent, 1000);
    }

    /**
     * 删除图片
     */
    private void deletePic(int position) {
        imageList.remove(position);
        bmpList.remove(position);

        adapter.notifyDataSetChanged();
    }

    /**
     * 添加按钮
     */
    private void addButton() {
        ImageBean bean = new ImageBean();
        bean.type = 0;
        bmpList.add(bean);

        adapter.notifyDataSetChanged();
    }

    /**
     * 添加图片
     */
    private void addBmp(Bitmap bmp) {
        ImageBean bean = new ImageBean();
        bean.bitmap = bmp;
        bean.path = StringUtils.bitmaptoString(bmp);
        bean.type = 1;
        bmpList.add(bmpList.size() - 1, bean);

        adapter.notifyDataSetChanged();
    }

    private UploadQuestionBean.UploadQuestionData problemkDetailData;

    /**
     * 获取问题详情
     */
    private void getProblemDetail() {
        GsonRequestHelper helper = new GsonRequestHelper(this);
        String url = ApiDefine.PROBLEM_DETAIL + problemBean.id;
        helper.sendGETRequest(url, UploadQuestionBean.UploadQuestionDetailData.class, false, null);
        helper.setOnResponseListener(new GsonRequestHelper.OnResponseListener() {
            @Override
            public void onError(VolleyError error) {

            }

            @Override
            public void onSuccess(Object data) {
                if (data != null) {
                    UploadQuestionBean.UploadQuestionDetailData bean = (UploadQuestionBean.UploadQuestionDetailData) data;
                    if (bean.code.equals("0")) {
                        UploadQuestionBean.UploadQuestionData detailData = bean.data;
                        problemkDetailData = detailData;

                        text_title.setText(detailData.title);
                        text_big_type.setText(getBigProblemName(detailData.problemType));
                        text_small_type.setText(detailData.problemClass);

                        getRegionText(detailData.region);

                        if (!TextUtils.isEmpty(detailData.reportPlace)) {
                            if (!TextUtils.isEmpty(detailData.latitude)) {
                                latitude = Double.parseDouble(detailData.latitude);
                            }
                            if (!TextUtils.isEmpty(detailData.longitude)) {
                                longitude = Double.parseDouble(detailData.longitude);
                            }

                            currentPlaceName = detailData.reportPlace;
                            edit_address.setText(detailData.reportPlace);
                        }
                        if (!TextUtils.isEmpty(detailData.projectId)) {
                            text_project_name.setText(detailData.projectName);

                            projectData = new QueryProjectBean.QueryProjectData();
                            projectData.id = detailData.projectId;
                            projectData.name = detailData.projectName;

                            findViewById(R.id.image_project_arrow).setVisibility(View.GONE);
                        } else {
                            findViewById(R.id.image_project_arrow).setVisibility(View.VISIBLE);
                            findViewById(R.id.layoutConnectedProject).setOnClickListener(new View.OnClickListener() {
                                @Override
                                public void onClick(View v) {
                                    selectProjectType();
                                }
                            });
                        }
                    } else if (bean.code.equals(IntentUtils.VAILD_CODE)) {
                        IntentUtils.skipToLogin(UploadZxActivity.this);
                    }
                }
            }
        });
    }

    /**
     * 获取定位
     */
    public void getLocationInfo() {
        initLocation();
    }

    private PoiSearch mPoiSearch;

    /**
     * 根据地址查询经纬度
     */
    private void getLatLng(String address) {
        mPoiSearch = new PoiSearch(this, new OnGetPoiResultListener() {
            @Override
            public void OnGetPoiResult(ArrayList<PoiInfo> arrayList, ArrayList<PoiSearch.ProvinceInfo> arrayList1, String s, int i) {
                if (arrayList != null && arrayList.size() > 0) {
                    longitude = arrayList.get(0).mPoint.getLongitudeE6();
                    latitude = arrayList.get(0).mPoint.getLatitudeE6();

                    uploadData();
                } else {
                    ToastUtils.showText(UploadZxActivity.this, "请输入正确的地址信息");
                    edit_address.requestFocus();
                    Utils.showSoftInputFromWindow(edit_address);
                }
            }
        }, RoundFragment.mMapView);
        mPoiSearch.search(address, null, null);
    }


    /**
     * 获取图片url
     */
    private String getImageListStr() {
        JSONArray jsonArray = new JSONArray();
        for (int i = 0; i < imageList.size(); i++) {
            ImageUploadBean bean = imageList.get(i);

            JSONObject jsonObject = new JSONObject();
            try {
                jsonObject.put("groupName", bean.groupName);
                jsonObject.put("photoType", bean.extName);
                jsonObject.put("photoUrl", bean.fileName);
            } catch (JSONException e) {
                e.printStackTrace();
            }
            jsonArray.put(jsonObject);
        }

        return jsonArray.toString();
    }

    private double latitude, longitude;

    private void initLocation() {
        edit_address.setText(currentPlaceName);
    }

    /**
     * 新增
     */
    private void uploadData() {
//        if (TextUtils.isEmpty(edit_address.getText().toString())) {
//            ToastUtils.showText(this, "请输入地址");
//            edit_address.requestFocus();
//            Utils.showSoftInputFromWindow(edit_address);
//            return;
//        }

        GsonRequestHelper helper = new GsonRequestHelper(this);
        Map<String, String> params = new HashMap<>();
        params.put("id", problemBean.id);
        params.put("reportPlace", edit_address.getText().toString());
        params.put("description", edit_description.getText().toString());
//        params.put("latitude", Utils.formatLatLng((float) (latitude / 1E6)));
//        params.put("longitude", Utils.formatLatLng((float) (longitude / 1E6)));
//        params.put("latitude", problemkDetailData.latitude);
//        params.put("longitude", problemkDetailData.longitude);
        params.put("photographer", SPHelper.getUid());
        params.put("problemSort", "3");
        params.put("problemType", problemkDetailData.problemType);
        params.put("problemClass", problemkDetailData.problemClass);
        params.put("region", problemkDetailData.region);
        params.put("areaName", textRegion.getText().toString());

        if (projectData != null) {
            params.put("projectId", projectData.id);
            params.put("projectName", projectData.name);
            params.put("projectType", projectType + "");
        }
//        params.put("serialNumber", text_serialNumber.getText().toString());
        params.put("title", text_title.getText().toString());
        params.put("problemPhotoUrls", getImageListStr());
        params.put("description", edit_description.getText().toString());

        helper.sendPOSTRequest(ApiDefine.PROBLEM_ADD, BaseBean.class, params, true, null);
        helper.setOnResponseListener(new GsonRequestHelper.OnResponseListener() {
            @Override
            public void onError(VolleyError error) {

            }

            @Override
            public void onSuccess(Object data) {
                if (data != null) {
                    BaseBean bean = (BaseBean) data;

                    if (bean.code.equals("0")) {
                        ToastUtils.showText(UploadZxActivity.this, "上报成功");
                        setResult(100);
                        finish();
                    } else {
                        ToastUtils.showText(UploadZxActivity.this, bean.msg);
                    }
                }
            }
        });
    }

    public void back(View view) {
        finish();
    }

    @Override
    public void onClick(View v) {

    }

    private String getBigProblemName(String value) {
        for (DictBean.DictData data : LinhuApp.problemTypeList) {
            if (value.equals(data.dictValue)) {
                return data.dictLabel;
            }
        }

        return "";
    }

    /**
     * 获取区域文本
     */
    private void getRegionText(String regionId) {
        GsonRequestHelper helper = new GsonRequestHelper(this);
        String url = ApiDefine.REGION_TEXT + regionId;
        helper.sendGETRequest(url, RegionTextBean.class, false, null);
        helper.setOnResponseListener(new GsonRequestHelper.OnResponseListener() {
            @Override
            public void onError(VolleyError error) {

            }

            @Override
            public void onSuccess(Object data) {
                if (data != null) {
                    RegionTextBean bean = (RegionTextBean) data;
                    if (bean.code.equals("0")) {
                        if (bean.data != null) {
                            if (!TextUtils.isEmpty(bean.data.name)) {
                                textRegion.setText(bean.data.name);
                            }
                        }
                    }
                }
            }
        });
    }

}
